import {
  makeAutoObservable,
  action,
  runInAction,
  toJS,
} from "mobx";
import Taro from "@tarojs/taro";
import {
  getBalance,
  getWalletMode,
  getChargeRecord,
  getWalletRecord,
  createChargeOrder,
  chargePrePayWechatMini,
  cancelOrder,
  ICreateChagrgeOrder,
  getOrderDetail,
  getPrice,
  IWalletOrder,
  IWalletConsume
} from '@/services/wallet';
import PageModel from '@/utils/PageModel';

const payTypeList = [12];

interface IWallet {
  balance: number;
  chargePageData: PageModel<IWalletOrder>;
  chargeDetail: any;
  consumePageData: PageModel<IWalletConsume>;
  consumeDetail: {};
}

class Wallet implements IWallet {
  constructor() {
    makeAutoObservable(this)
  }

  walletMode = [];

  balance = 0;

  chargePageData: PageModel<IWalletOrder> = new PageModel<IWalletOrder>();

  chargeDetail: any;

  consumePageData: PageModel<IWalletConsume> = new PageModel<IWalletConsume>();

  consumeDetail = {};

  price = {};

  @action
  async getPrice() {
    const res = await getPrice();
    if (res.success) {
      // 1短信 2语音
      this.price = res.data;
      return this.price;
    }
  }

  @action
  async getBalance() {
    const res = await getBalance();
    if (res.success) {
      this.balance = res.data.gizwitsCoin;
      return this.balance;
    }
  }

  @action
  async cancelChargeOrder(orderNo: string) {
    const res = await cancelOrder(orderNo);
    if (res.success) {
      const newChargeData = [...this.chargePageData.records];
      newChargeData.forEach((item: any) => {
        if (item.orderNo === orderNo) {
          item.status = -1;
        }
      });
      this.chargePageData.records = newChargeData;
      this.chargePageData = { ...this.chargePageData };
      if (this.chargeDetail) {
        this.chargeDetail.status = -1;
      }

    }
  }

  @action
  async getWalletMode() {
    // 小程序按安卓平台处理，传1
    const res = await getWalletMode(1);
    if (res.success) {
      this.walletMode = res.data;
      return this.walletMode;
    }
  }

  @action
  async createAndPay(params: ICreateChagrgeOrder) {
    console.log('createAndPay', params.payType);
    // const payType = Platform.OS === 'android' ? params.payType : 'APPLE_IAP';
    const payType = params.payType;
    const orderRes = await createChargeOrder({ ...params, payType });
    if (orderRes.success) {
      let type = 2;
      switch (payType) {
        case 'APPLE_IAP':
          type = 10;
          break;
        case 'WX_APP':
          type = 2;
          break;
        case 'WX_MINI':
          type = 12;
          break;
        default:
          type = 3;
          break;
      }
      const payRes = await this.pay({
        orderNo: orderRes.data.orderNo,
        payType: type,
        productId: orderRes.data.chargeModeAdditionalData,
      });

      return payRes;
    }
    return { isSuccess: false };
  }

  @action
  async pay({
    orderNo,
    payType,
    productId,
  }: {
    orderNo: string;
    payType: number;
    productId?: string;
  }) {
    console.log('pay', orderNo, payType, productId);
    // 2微信支付 3支付宝支付 10苹果内购
    let prePayRes: any;
    let payRes;
    if (payType === 12) {
      prePayRes = await chargePrePayWechatMini({ orderNo, payType: 'WX_MINI' });
      if (prePayRes.success) {
        payRes = await this.wechatPay(prePayRes.data);
      } else {
        prePayRes.isSuccess = false;
        payRes = prePayRes;
      }
    }
    return payRes;
  }

  @action
  wechatPay(params: any) {
    return new Promise((resolve, reject) => {
      const {
        wxPayInfo: {
        partnerid: partnerId,
        prepayid: prepayId,
        noncestr: nonceStr,
        timestamp: timeStamp,
        package: packageStr,
        paySign: sign,
        timeout = 60,
        }
      } = params;
      const resObj: any = {
        payRes: null,
        isSuccess: false,
      };
      const timer = setTimeout(() => {
        // console.log('微信支付超时');
        resolve({ isSuccess: false, error: { message: '支付超时' } })
      }, timeout * 1000);
      const packageString = `prepay_id=${prepayId}`;
      try {
        console.log('支付参数', {
          timeStamp,
          nonceStr,
          paySign: sign,
          package: packageString,
          signType: 'MD5',
        });
        Taro.requestPayment({
          timeStamp,
          nonceStr,
          paySign: sign,
          package: packageString,
          signType: 'MD5',
          success: (res) => {
            console.log("支付成功结果：", res)
            resObj.payRes = res;
            resObj.isSuccess = true;
            clearTimeout(timer);
            resolve(resObj);
          },
          fail: (error) => {
            console.log("支付成功结果：", error)
            resObj.payRes = error;
            resObj.isSuccess = false;
            clearTimeout(timer);
            resolve(resObj);
          }
        })
      } catch (error: any) {
        // console.log(error, '微信支付抛错');
        clearTimeout(timer);
        resolve(resObj);
      }
    })
  }

  @action
  async getChargeRecord(current: number) {
    const res = await getChargeRecord({
      size: 20,
      current,
      query: {
        orderType: 1,
      },
    });
    if (res.success) {
      console.log('this.chargePageData', this.chargePageData);
      const tmp = new PageModel(toJS(this.chargePageData));
      tmp.updateRecords(res.data as PageModel<IWalletOrder>);
      this.chargePageData = tmp;
    }
    return res;
  }

  @action
  async setChargeDetail(orderNo: number) {
    const res = await getOrderDetail(`${orderNo}`);
    let detail = {};
    if (res.success) {
      detail = {
        ...res.data,
        tradeNo: res.data.tradeVO ? res.data.tradeVO.tradeNo : null,
      };
      // 写入新数据
      this.chargePageData.records.forEach((item, index) => {
        if (item.orderNo === orderNo) {
          this.chargePageData.records = [
            ... this.chargePageData.records.slice(0, index),
            detail,
            ... this.chargePageData.records.slice(index + 1),
          ];
        }
      });
    } else {
      detail = this.chargePageData.records.find(i => i.orderNo === orderNo) || {};
    }
    this.chargeDetail = detail;
  }

  @action
  async getConsumeRecord(
    current: number,
    startTime: any,
    endTime: any,
    sno?: any
  ) {
    const res = await getWalletRecord({
      size: 20,
      current,
      query: {
        orderType: 2,
        startTime,
        endTime,
        status: 2,
        sno,
      },
    });
    if (res.success) {
      const tmp = new PageModel(toJS(this.consumePageData));
      tmp.updateRecords(res.data as PageModel<IWalletConsume>);
      runInAction(() => {
        this.consumePageData = tmp;
      });
    }
  }

  @action
  async setConsumeDetail(orderNo: number) {
    const detail = this.consumePageData.records.find((i: any) => i.orderNo === orderNo) || {};
    this.consumeDetail = detail;
  }

  @action
  resetConsumeRecord() {
    this.consumePageData = new PageModel<IWalletConsume>();;
  }

  @action
  supportPayTypeList() {
    return payTypeList;
  }


}

const Wallet_Store_Key = "wallet";

export { Wallet, Wallet_Store_Key };

export default new Wallet();
